/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.app.pay.wallet.service.impl;

import com.shop.cereshop.app.pay.wallet.service.WalletPayService;
import com.shop.cereshop.app.service.wallet.BuyerWalletService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.enums.TransactionTypeEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service(value = "walletPayService")
@Slf4j(topic = "WalletPayServiceImpl")
public class WalletPayServiceImpl implements WalletPayService {

    @Autowired
    private BuyerWalletService buyerWalletService;

    @Override
    public Map<String, String> gotoPay(String orderFormId, BigDecimal money, String openid, String ip, Integer type, Integer huabeiPeriod) throws CoBusinessException, Exception {
        Map<String, String> result = new HashMap<>();

        try {
            // 钱包支付不需要openid，直接使用用户ID
            Long buyerUserId = Long.parseLong(openid);

            // 生成钱包支付订单号
            String walletOrderNo = "WALLET" + orderFormId + RandomStringUtil.getRandomCode(3, 0);

            // 调用钱包消费服务
            boolean success = buyerWalletService.consume(
                buyerUserId,
                money,
                    TransactionTypeEnum.CONSUME.getCode(),
                "订单支付：" + orderFormId,
                walletOrderNo,
                null, // 钱包支付不需要支付密码验证
                ip
            );

            if (success) {
                // 钱包支付成功，返回符合前端SDK调用的格式
                result.put("return_code", "SUCCESS");
                result.put("return_msg", "钱包支付成功");
                result.put("transaction_id", walletOrderNo);
                result.put("out_trade_no", walletOrderNo);

                // 设置前端SDK需要的字段（模拟微信支付格式）
                result.put("appId", "WALLET_PAY");
                result.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
                result.put("nonceStr", RandomStringUtil.getRandomCode(32, 0));
                result.put("signType", "RSA");
                result.put("paySign", "WALLET_PAY_SUCCESS");
                result.put("codeUrl", "");
                result.put("mwebUrl", "");
                result.put("partnerId", "");
                result.put("tradeNo", walletOrderNo);
                result.put("prepayId", walletOrderNo);
                result.put("packages", "prepay_id=" + walletOrderNo);

                // 添加钱包支付特有字段
                result.put("paymentType", "WALLET");
                result.put("walletOrderNo", walletOrderNo);
                result.put("walletBalance", "0"); // 支付后余额，需要从钱包服务获取
            } else {
                // 钱包支付失败，抛出异常让上层处理
                throw new CoBusinessException(CoReturnFormat.WALLET_BALANCE_INSUFFICIENT);
            }

        } catch (Exception e) {
            log.error("钱包支付失败", e);
            result.put("return_code", "FAIL");
            result.put("return_msg", "钱包支付异常：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, String> refund(String transactionId, String outRefundNo, BigDecimal total, BigDecimal refund) throws CoBusinessException, Exception {
        Map<String, String> result = new HashMap<>();

        try {
            // 钱包退款逻辑 - 直接退回到钱包余额
            // 这里需要从transactionId中解析出用户ID和订单信息
            // 简化处理：假设transactionId格式为 "WALLET{orderId}{randomCode}"
            String orderId = transactionId.replace("WALLET", "").substring(0, transactionId.length() - 4);

            // 钱包退款逻辑 - 直接退回到钱包余额
            // 这里需要从订单中获取用户ID，简化处理
            // TODO: 需要从订单表中查询用户ID
            log.warn("钱包退款功能需要完善：需要从订单中获取用户ID");
            result.put("return_code", "FAIL");
            result.put("return_msg", "钱包退款功能暂未完善");

        } catch (Exception e) {
            log.error("钱包退款失败", e);
            result.put("return_code", "FAIL");
            result.put("return_msg", "钱包退款异常：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, String> orderRefund(String transactionId, String outRefundNo, BigDecimal total, BigDecimal refund) throws CoBusinessException, Exception {
        // 订单退款和普通退款逻辑相同
        return refund(transactionId, outRefundNo, total, refund);
    }

    @Override
    public Map<String, String> refundBond(String transactionId, String outRefundNo, BigDecimal total, BigDecimal refund) throws CoBusinessException, Exception {
        // 保证金退款和普通退款逻辑相同
        return refund(transactionId, outRefundNo, total, refund);
    }

    @Override
    public String getCollectionCode(String orderFormId, BigDecimal money, String ip, String tradeType) throws CoBusinessException, Exception {
        // 钱包支付不需要生成收款码，直接返回成功
        return "WALLET_PAY_SUCCESS";
    }

    @Override
    public String getOrderCollectionCode(String orderFormId, BigDecimal money, String ip, String tradeType) throws CoBusinessException, Exception {
        // 钱包支付不需要生成收款码，直接返回成功
        return "WALLET_PAY_SUCCESS";
    }
}
